package com.thread.wait;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangyingjie
 * @date
 * @remark
 */
public class ConditionDemo extends Thread{

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition condition = lock.newCondition();

    public ConditionDemo(String name) {
        super.setName(name);
    }

    @Override
    public void run() {
        lock.lock();
        try {
            System.out.println(this.getName()+"进入临界区，阻塞。。。");
            condition.await();
            System.out.println(this.getName()+"唤醒继续执行。。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new ConditionDemo("t1");
        Thread t2 = new ConditionDemo("t2");
        t1.start();
        Thread.sleep(100);
        t2.start();
        Thread.sleep(100);
        lock.lock();
        //唤醒阻塞的线程
        condition.signal();
        //唤醒之后一般会释放锁，让阻塞线程去执行。因为await()阻塞线程唤醒后还会去获取一遍锁
        lock.unlock();
    }
}
